﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace KiDS_Projekat
{
	public class PullDataCommand : Command
	{
		private string _command;
		private Node _myNode;
	
		public PullDataCommand(SOCKET socket, string p, Node myNode)
		 :base(socket){
			 _command = CommandFactory.NormalizeLocation(p);
			 _myNode = myNode;
			
		}
		public override void DoCommmand()
		{
			List<ExternalNode> collection = _myNode.CollectedTemperatures;
			double midValue = 0;
			int count = 0;
	
			foreach (var temp in collection)
			{
				if (temp.Location.Contains(_command))
				{
					midValue += temp.Temperature;
					count++;
				}
			}
			if (count > 0)
			{
				Program.Terminal.Print("Sending temp: " + (midValue / count) * 100);
				Native.SendMessage(CMD.CMD_REPLY_OK.ParseInt() + " " + (midValue / count) * 100, _socket);
			}
			else
			{
				//split location, pokusati sa svakom lokacijom koja
				string[] location = _command.Split(',').Reverse().ToArray();
				int i = 0; 
				while (i < location.Length)
				{
					foreach (var item in _myNode.Masters)
					{
						if (item.Key.Contains(location[i]))
						{
							Program.Terminal.Print("Sending request to " + item.Value[0].Location);
							for (int j = 0; j < item.Value.Count; j++)
							{
								if(item.Value[j].Port != _myNode.Port){
									Client client = new Client(item.Value[j].Address, item.Value[j].Port);
									client.Open();
									client.SendMessage(CMD.CMD_PULL_DATA.ParseInt() + " " + _command);
									string response = client.RecieveMessage();
									Program.Terminal.Print(response);
									client.Close();
									if (response.StartsWith((CMD.CMD_REPLY_OK.ParseInt())))
									{
										Native.SendMessage(CMD.CMD_REPLY_OK.ParseInt() + " " + response.Split(' ')[1], _socket);
										_myNode.CollectTemperature(_command, Double.Parse(response.Split(' ')[1]));
										Native.closesocket(_socket);
										return;
									}
								}
							}
							
							
						}
					}
					i++;
				}
					
				Native.SendMessage(CMD.CMD_REPLY_FAIL.ParseInt() + " " + CMD.ERROR_GEOLEVEL_NOT_FOUND.ParseInt(), _socket);
			}
				
			Native.closesocket(_socket);
		}
	}
}
